[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { useCurrentGrowiLayoutFluidClassName } from '~/client/services/layout';
  19. import { PageView } from '~/components/Page/PageView';
  20. import RevisionRenderer from '~/components/Page/RevisionRenderer';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  22. import type { CrowiRequest } from '~/interfaces/crowi-request';
  23. import type { EditorConfig } from '~/interfaces/editor-settings';
  24. import type { IPageGrantData } from '~/interfaces/page';
  25. import type { RendererConfig } from '~/interfaces/services/renderer';
  26. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  27. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  28. import type { PageModel, PageDocument } from '~/server/models/page';
  29. import type { PageRedirectModel } from '~/server/models/page-redirect';
  30. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  31. import { generateSSRViewOptions } from '~/services/renderer/renderer';
  32. import { useEditingMarkdown } from '~/stores/editor';
  33. import { useHasDraftOnHackmd, usePageIdOnHackmd, useRevisionIdHackmdSynced } from '~/stores/hackmd';
  34. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  35. import { useRedirectFrom } from '~/stores/page-redirect';
  36. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  37. import {
  38. useSelectedGrant,
  39. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  40. } from '~/stores/ui';
  41. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  42. import loggerFactory from '~/utils/logger';
  43. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  44. import { BasicLayoutWithEditorMode } from '../components/Layout/BasicLayout';
  45. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  46. import type { GrowiSubNavigationSwitcherProps } from '../components/Navbar/GrowiSubNavigationSwitcher';
  47. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  48. import {
  49. useCurrentUser,
  50. useIsLatestRevision,
  51. useIsForbidden, useIsNotFound, useIsSharedUser,
  52. useIsEnabledStaleNotification, useIsIdenticalPath,
  53. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  54. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  55. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  56. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  57. useIsSlackConfigured, useRendererConfig,
  58. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  59. } from '../stores/context';
  60. import { NextPageWithLayout } from './_app.page';
  61. import {
  62. CommonProps, getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage,
  63. } from './utils/commons';
  64. declare global {
  65. // eslint-disable-next-line vars-on-top, no-var
  66. var globalEmitter: EventEmitter;
  67. }
  68. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  69. const GrowiSubNavigationSwitcher = dynamic<GrowiSubNavigationSwitcherProps>(() => import('../components/Navbar/GrowiSubNavigationSwitcher')
  70. .then(mod => mod.GrowiSubNavigationSwitcher), { ssr: false });
  71. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  72. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  73. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  74. const logger = loggerFactory('growi:pages:all');
  75. const {
  76. isPermalink: _isPermalink, isTrashPage: _isTrashPage, isCreatablePage,
  77. } = pagePathUtils;
  78. const { removeHeadingSlash } = pathUtils;
  79. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  80. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  81. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  82. {
  83. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  84. return v?.data != null
  85. && v?.data.toObject != null
  86. && v?.meta != null
  87. && isIPageInfoForEntity(v.meta);
  88. },
  89. serialize: (v) => {
  90. return {
  91. data: superjson.stringify(v.data.toObject()),
  92. meta: superjson.stringify(v.meta),
  93. };
  94. },
  95. deserialize: (v) => {
  96. return {
  97. data: superjson.parse(v.data),
  98. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  99. };
  100. },
  101. },
  102. 'IPageToShowRevisionWithMetaTransformer',
  103. );
  104. // GrowiContextualSubNavigation for NOT shared page
  105. type GrowiContextualSubNavigationProps = {
  106. isLinkSharingDisabled: boolean,
  107. }
  108. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  109. const { isLinkSharingDisabled } = props;
  110. const { data: currentPage } = useSWRxCurrentPage();
  111. return (
  112. <div data-testid="grw-contextual-sub-nav">
  113. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled}/>
  114. </div>
  115. );
  116. };
  117. const PutbackPageModal = (): JSX.Element => {
  118. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  119. return <PutbackPageModal />;
  120. };
  121. type Props = CommonProps & {
  122. currentUser: IUser,
  123. pageWithMeta: IPageToShowRevisionWithMeta | null,
  124. // pageUser?: any,
  125. redirectFrom?: string;
  126. // shareLinkId?: string;
  127. isLatestRevision?: boolean,
  128. isIdenticalPathPage?: boolean,
  129. isForbidden: boolean,
  130. isNotFound: boolean,
  131. isNotCreatable: boolean,
  132. // isAbleToDeleteCompletely: boolean,
  133. templateTagData?: string[],
  134. templateBodyData?: string,
  135. isSearchServiceConfigured: boolean,
  136. isSearchServiceReachable: boolean,
  137. isSearchScopeChildrenAsDefault: boolean,
  138. isSlackConfigured: boolean,
  139. // isMailerSetup: boolean,
  140. isAclEnabled: boolean,
  141. // hasSlackConfig: boolean,
  142. drawioUri: string | null,
  143. hackmdUri: string,
  144. noCdn: string,
  145. // highlightJsStyle: string,
  146. isAllReplyShown: boolean,
  147. isContainerFluid: boolean,
  148. editorConfig: EditorConfig,
  149. isEnabledStaleNotification: boolean,
  150. isEnabledAttachTitleHeader: boolean,
  151. // isEnabledLinebreaks: boolean,
  152. // isEnabledLinebreaksInComments: boolean,
  153. adminPreferredIndentSize: number,
  154. isIndentSizeForced: boolean,
  155. disableLinkSharing: boolean,
  156. grantData?: IPageGrantData,
  157. rendererConfig: RendererConfig,
  158. // UI
  159. userUISettings?: IUserUISettings
  160. // Sidebar
  161. sidebarConfig: ISidebarConfig,
  162. };
  163. const Page: NextPageWithLayout<Props> = (props: Props) => {
  164. // const { t } = useTranslation();
  165. const router = useRouter();
  166. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  167. // register global EventEmitter
  168. if (isClient() && window.globalEmitter == null) {
  169. window.globalEmitter = new EventEmitter();
  170. }
  171. // commons
  172. useEditorConfig(props.editorConfig);
  173. useCsrfToken(props.csrfToken);
  174. // UserUISettings
  175. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  176. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  177. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  178. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  179. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  180. // page
  181. useIsLatestRevision(props.isLatestRevision);
  182. useIsContainerFluid(props.isContainerFluid);
  183. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  184. useIsForbidden(props.isForbidden);
  185. useIsNotFound(props.isNotFound);
  186. useIsNotCreatable(props.isNotCreatable);
  187. useRedirectFrom(props.redirectFrom ?? null);
  188. useIsSharedUser(false); // this page cann't be routed for '/share'
  189. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  190. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  191. useIsSearchPage(false);
  192. useTemplateTagData(props.templateTagData);
  193. useTemplateBodyData(props.templateBodyData);
  194. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  195. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  196. useIsSearchServiceReachable(props.isSearchServiceReachable);
  197. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  198. useIsSlackConfigured(props.isSlackConfigured);
  199. // useIsMailerSetup(props.isMailerSetup);
  200. useIsAclEnabled(props.isAclEnabled);
  201. // useHasSlackConfig(props.hasSlackConfig);
  202. useDrawioUri(props.drawioUri);
  203. useHackmdUri(props.hackmdUri);
  204. // useNoCdn(props.noCdn);
  205. useDefaultIndentSize(props.adminPreferredIndentSize);
  206. useIsIndentSizeForced(props.isIndentSizeForced);
  207. useDisableLinkSharing(props.disableLinkSharing);
  208. useRendererConfig(props.rendererConfig);
  209. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  210. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  211. useIsAllReplyShown(props.isAllReplyShown);
  212. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  213. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  214. const { pageWithMeta, userUISettings } = props;
  215. const pageId = pageWithMeta?.data._id;
  216. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  217. const revisionBody = pageWithMeta?.data.revision?.body;
  218. useCurrentPageId(pageId ?? null);
  219. useRevisionIdHackmdSynced(pageWithMeta?.data.revisionHackmdSynced);
  220. useRemoteRevisionId(pageWithMeta?.data.revision?._id);
  221. usePageIdOnHackmd(pageWithMeta?.data.pageIdOnHackmd);
  222. useHasDraftOnHackmd(pageWithMeta?.data.hasDraftOnHackmd ?? false);
  223. useCurrentPathname(props.currentPathname);
  224. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  225. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  226. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  227. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  228. useSetupGlobalSocket();
  229. useSetupGlobalSocketForPage(pageId);
  230. const growiLayoutFluidClass = useCurrentGrowiLayoutFluidClassName();
  231. const shouldRenderPutbackPageModal = pageWithMeta != null
  232. ? _isTrashPage(pageWithMeta.data.path)
  233. : false;
  234. // sync grant data
  235. useEffect(() => {
  236. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  237. mutateSelectedGrant(grantDataToApply);
  238. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  239. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  240. useEffect(() => {
  241. const decodedURI = decodeURI(window.location.pathname);
  242. if (isClient() && decodedURI !== props.currentPathname) {
  243. const { search, hash } = window.location;
  244. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  245. }
  246. }, [props.currentPathname, router]);
  247. // initialize mutateEditingMarkdown only once per page
  248. useEffect(() => {
  249. mutateEditingMarkdown(revisionBody);
  250. }, [mutateEditingMarkdown, revisionBody]);
  251. const title = generateCustomTitleForPage(props, pagePath);
  252. // TODO: show SSR body
  253. // const rendererOptions = generateSSRViewOptions(props.rendererConfig, pagePath);
  254. // const ssrBody = <RevisionRenderer rendererOptions={rendererOptions} markdown={revisionBody ?? ''} />;
  255. return (
  256. <>
  257. <Head>
  258. <title>{title}</title>
  259. </Head>
  260. <div className={`dynamic-layout-root ${growiLayoutFluidClass} h-100 d-flex flex-column justify-content-between`}>
  261. <header className="py-0 position-relative">
  262. <div id="grw-subnav-container">
  263. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  264. </div>
  265. </header>
  266. <div className="d-edit-none">
  267. <GrowiSubNavigationSwitcher isLinkSharingDisabled={props.disableLinkSharing} />
  268. </div>
  269. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  270. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  271. <DisplaySwitcher
  272. pageView={
  273. <PageView
  274. pagePath={pagePath}
  275. page={pageWithMeta?.data}
  276. // TODO: show SSR body
  277. // ssrBody={ssrBody}
  278. />
  279. }
  280. />
  281. <PageStatusAlert />
  282. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  283. </div>
  284. </>
  285. );
  286. };
  287. Page.getLayout = function getLayout(page) {
  288. return (
  289. <>
  290. <DrawioViewerScript />
  291. <BasicLayoutWithEditorMode>
  292. {page}
  293. </BasicLayoutWithEditorMode>
  294. <UnsavedAlertDialog />
  295. <DescendantsPageListModal />
  296. <DrawioModal />
  297. <HandsontableModal />
  298. </>
  299. );
  300. };
  301. function getPageIdFromPathname(currentPathname: string): string | null {
  302. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  303. }
  304. class MultiplePagesHitsError extends ExtensibleCustomError {
  305. pagePath: string;
  306. constructor(pagePath: string) {
  307. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  308. this.pagePath = pagePath;
  309. }
  310. }
  311. // apply parent page grant fot creating page
  312. async function applyGrantToPage(props: Props, ancestor: any) {
  313. await ancestor.populate('grantedGroup');
  314. const grant = {
  315. grant: ancestor.grant,
  316. };
  317. const grantedGroup = ancestor.grantedGroup ? {
  318. grantedGroup: {
  319. id: ancestor.grantedGroup.id,
  320. name: ancestor.grantedGroup.name,
  321. },
  322. } : {};
  323. props.grantData = Object.assign(grant, grantedGroup);
  324. }
  325. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  326. const { model: mongooseModel } = await import('mongoose');
  327. const req: CrowiRequest = context.req as CrowiRequest;
  328. const { crowi } = req;
  329. const { revisionId } = req.query;
  330. const Page = crowi.model('Page') as PageModel;
  331. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  332. const { pageService } = crowi;
  333. let currentPathname = props.currentPathname;
  334. const pageId = getPageIdFromPathname(currentPathname);
  335. const isPermalink = _isPermalink(currentPathname);
  336. const { user } = req;
  337. if (!isPermalink) {
  338. // check redirects
  339. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  340. if (chains != null) {
  341. // overwrite currentPathname
  342. currentPathname = chains.end.toPath;
  343. props.currentPathname = currentPathname;
  344. // set redirectFrom
  345. props.redirectFrom = chains.start.fromPath;
  346. }
  347. // check whether the specified page path hits to multiple pages
  348. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  349. if (count > 1) {
  350. throw new MultiplePagesHitsError(currentPathname);
  351. }
  352. }
  353. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  354. const page = pageWithMeta?.data as unknown as PageDocument;
  355. // add user to seen users
  356. if (page != null && user != null) {
  357. await page.seen(user);
  358. }
  359. // populate & check if the revision is latest
  360. if (page != null) {
  361. page.initLatestRevisionField(revisionId);
  362. await page.populateDataToShowRevision();
  363. props.isLatestRevision = page.isLatestRevision();
  364. }
  365. if (page == null && user != null) {
  366. const templateData = await Page.findTemplate(props.currentPathname);
  367. if (templateData != null) {
  368. props.templateTagData = templateData.templateTags as string[];
  369. props.templateBodyData = templateData.templateBody as string;
  370. }
  371. // apply pagrent page grant
  372. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  373. if (ancestor != null) {
  374. await applyGrantToPage(props, ancestor);
  375. }
  376. }
  377. props.pageWithMeta = pageWithMeta;
  378. }
  379. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  380. const { model: mongooseModel } = await import('mongoose');
  381. const req = context.req as CrowiRequest<IUserHasId & any>;
  382. const { user } = req;
  383. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  384. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  385. if (userUISettings != null) {
  386. props.userUISettings = userUISettings.toObject();
  387. }
  388. }
  389. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  390. const req: CrowiRequest = context.req as CrowiRequest;
  391. const { crowi } = req;
  392. const Page = crowi.model('Page') as PageModel;
  393. const { currentPathname } = props;
  394. const pageId = getPageIdFromPathname(currentPathname);
  395. const isPermalink = _isPermalink(currentPathname);
  396. const page = props.pageWithMeta?.data;
  397. if (props.isIdenticalPathPage) {
  398. props.isNotCreatable = true;
  399. }
  400. else if (page == null) {
  401. props.isNotFound = true;
  402. props.isNotCreatable = !isCreatablePage(currentPathname);
  403. // check the page is forbidden or just does not exist.
  404. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  405. props.isForbidden = count > 0;
  406. }
  407. else {
  408. props.isNotFound = page.isEmpty;
  409. props.isNotCreatable = false;
  410. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  411. if (isPermalink && page.isEmpty) {
  412. props.currentPathname = page.path;
  413. }
  414. // /path/to/page ==> /62a88db47fed8b2d94f30000
  415. if (!isPermalink && !page.isEmpty) {
  416. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  417. if (!isToppage) {
  418. props.currentPathname = `/${page._id}`;
  419. }
  420. }
  421. }
  422. }
  423. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  424. // const req: CrowiRequest = context.req as CrowiRequest;
  425. // const { crowi } = req;
  426. // const UserModel = crowi.model('User');
  427. // if (isUserPage(props.currentPagePath)) {
  428. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  429. // if (user != null) {
  430. // props.pageUser = JSON.stringify(user.toObject());
  431. // }
  432. // }
  433. // }
  434. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  435. const req: CrowiRequest = context.req as CrowiRequest;
  436. const { crowi } = req;
  437. const {
  438. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  439. } = crowi;
  440. props.isSearchServiceConfigured = searchService.isConfigured;
  441. props.isSearchServiceReachable = searchService.isReachable;
  442. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  443. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  444. // props.isMailerSetup = mailService.isMailerSetup;
  445. props.isAclEnabled = aclService.isAclEnabled();
  446. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  447. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  448. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  449. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  450. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  451. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  452. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  453. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  454. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  455. props.editorConfig = {
  456. upload: {
  457. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  458. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  459. },
  460. };
  461. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  462. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  463. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  464. props.rendererConfig = {
  465. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  466. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  467. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  468. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  469. plantumlUri: process.env.PLANTUML_URI ?? null,
  470. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  471. // XSS Options
  472. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  473. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  474. attrWhiteList: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  475. tagWhiteList: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  476. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  477. };
  478. props.sidebarConfig = {
  479. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  480. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  481. };
  482. }
  483. /**
  484. * for Server Side Translations
  485. * @param context
  486. * @param props
  487. * @param namespacesRequired
  488. */
  489. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  490. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  491. props._nextI18Next = nextI18NextConfig._nextI18Next;
  492. }
  493. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  494. const req = context.req as CrowiRequest<IUserHasId & any>;
  495. const { user } = req;
  496. const result = await getServerSideCommonProps(context);
  497. // check for presence
  498. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  499. if (!('props' in result)) {
  500. throw new Error('invalid getSSP result');
  501. }
  502. const props: Props = result.props as Props;
  503. if (props.redirectDestination != null) {
  504. return {
  505. redirect: {
  506. permanent: false,
  507. destination: props.redirectDestination,
  508. },
  509. };
  510. }
  511. if (user != null) {
  512. props.currentUser = user.toObject();
  513. }
  514. try {
  515. await injectPageData(context, props);
  516. }
  517. catch (err) {
  518. if (err instanceof MultiplePagesHitsError) {
  519. props.isIdenticalPathPage = true;
  520. }
  521. else {
  522. throw err;
  523. }
  524. }
  525. await injectUserUISettings(context, props);
  526. await injectRoutingInformation(context, props);
  527. injectServerConfigurations(context, props);
  528. await injectNextI18NextConfigurations(context, props, ['translation']);
  529. return {
  530. props,
  531. };
  532. };
  533. export default Page;